package user

import (
	"github.com/bgmp/config"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
	"time"
)

func (b Base) Report(c *gin.Context, req *ReportRequest) *ReportResponse {
	req.EndTime.Time = time.Date(req.EndTime.Time.Year(), req.EndTime.Month(), req.EndTime.Day(), 23, 59, 59, 0, req.EndTime.Time.Location())
	response := ReportResponse{}

	delta := -3 * time.Hour

	condition := model.BgSelectConditions{
		Start: model.Time{Time: req.EndTime.Time.Add(delta)},
		End:   model.Time{Time: req.EndTime.Time},
	}

	for i := 1; i <= 7; i++ {
		var withinDay []float64

		for j := 1; j <= 8; j++ {
			bgs := model.ListBgViews(config.DB,
				map[string]any{model.Bg_UserId: middleware.GetUserId(c)},
				&condition,
			)
			// 求均值
			average := 0.0
			for _, bg := range bgs {
				average += bg.Value
				if bg.Value > 6.1 {
					response.High++
				} else if bg.Value < 3.9 {
					response.Low++
				} else {
					response.Normal++
				}
			}
			length := len(bgs)
			if length > 0 {
				average = average / float64(length)
				response.Total += length
			}
			withinDay = append(withinDay, average)

			//fmt.Println(fmt.Sprintf("%s %s %f", condition.Start.Time, condition.End.Time, average))

			// 减少3个小时
			condition.Start.Time = condition.Start.Time.Add(delta)
			condition.End.Time = condition.End.Add(delta)

		}
		response.Average = append(response.Average, withinDay)
	}

	return &response
}

type ReportRequest struct {
	EndTime model.Time `json:"end_time"`
}

type ReportResponse struct {
	Average [][]float64 `json:"average"`
	Total   int         `json:"total"`
	Normal  int         `json:"normal"`
	High    int         `json:"high"`
	Low     int         `json:"low"`
}
